<template>
  <div :class="className" :style="{height:height,width:width}"></div>
</template>

<script>
import echarts from 'echarts'
import moment from 'moment'
import { debounce } from '@/utils'
require('echarts/theme/macarons')

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    dataList: {}
  },
  data() {
    return {
      chart: null,
      list: []
    }
  },
  watch: {
    dataList(val) {
      this.list = val
      this.initChart()
    }
  },
  mounted() {
    this.__resizeHanlder = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHanlder)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHanlder)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      const timeArray = []
      const dataArray = []
      const now = moment().format('YYYY/MM/DD HH').substr(5, 9) + ':00'
      for (var index in this.list) {
        const canTime = this.list[index].time.substr(5, 11).replace('-', '/')
        timeArray.push(canTime)
        dataArray.push(this.list[index].parkInCars)
        if (canTime === now) {
          break
        }
      }
      this.chart = echarts.init(this.$el, 'macarons')
      this.chart.setOption({
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          name: '停车时间',
          type: 'category',
          data: timeArray
        },
        yAxis: {
          name: '停车数量',
          type: 'value',
          splitLine: {
            show: false
          }
        },
        grid: {
          x: '3.8%',
          y: '17.3%',
          x2: '5.5%',
          y2: '17%'
        },
        visualMap: {
          orient: 'horizontal',
          top: 10,
          right: 'right',
          textStyle: {
            fontSize: 12,
            color: '#85B8D9'
          }, pieces: [{
            gt: 100,
            lte: 300,
            color: '#ffde33'
          }, {
            gt: 300,
            lte: 800,
            color: '#cc0033'
          }, {
            gt: 800,
            color: '#660099'
          }],
          outOfRange: {
            color: '#6ea1ff'
          }
        },
        series: [{
          data: dataArray,
          type: 'line',
          markLine: {
            // silent: true,
            data: [{
              yAxis: 100
            }, {
              yAxis: 300
            }, {
              yAxis: 800
            }]
          }
        }]
      })
    }
  }
}
</script>
